package com.kystar.muxplayer.protocol.connection;

import android_serialport_api.SerialPort;
import com.kystar.muxplayer.base.TLog;
import com.kystar.muxplayer.protocol.CodeCmd;
import com.kystar.muxplayer.protocol.Connection;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeoutException;

public class DeviceConnection implements Connection {

    public static final String PORT = "ttyS0";
    public static final int BAUDRATE = 115200;

    public static final long TIME_OUT = 20000;

    private final InputStream mInputStream;
    private final OutputStream mOutputStream;
    private final SerialPort mSerialPort;
    public DeviceConnection() throws IOException {
        mSerialPort = new SerialPort(new File("/dev/" + PORT), BAUDRATE, 0);
        mInputStream = mSerialPort.inputStream;
        mOutputStream = mSerialPort.outputStream;
    }

    @Override
    public void close() {
        close(mInputStream);
        close(mOutputStream);
        close(mSerialPort);
    }


    @Override
    public void write(CodeCmd cmd) throws IOException, TimeoutException {//阻塞当前方法
//        synchronized (DeviceConnection.class) {

            mOutputStream.write(cmd.getValue());
            long time = 0;
            while (mInputStream.available() == 0) {
                if (time > TIME_OUT) {
                    TLog.e("timeout");
                    throw new TimeoutException();
                }
                try {
                    Thread.sleep(100);
                    time += 100;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            cmd.process(mInputStream);
//        }
    }
    public static void close(Closeable c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
